proc genkey {lock {seed 5}} {
	if {[string length $lock] < 3} {
		return -code error "lock is less than 3 characters long"
	}

	set L {}
	foreach c [split $lock ""] {
		scan $c %c n
		lappend L $n
	}

	set K {}
	lappend K [expr {
		[lindex $L 0] ^ [lindex $L end] ^ [lindex $L end-1] ^ $seed
	}]

	set b [lindex $L 0]
	foreach a [lrange $L 1 end] {
		lappend K [expr {$a ^ $b}]
		set b $a
	}

	set key ""
	foreach n $K {
		set c [expr {(($n << 4) | ($n >> 4)) & 255}]
		append key [format %c $c]
	}
 
	string map {
		\u0000    /%DCN000%/
		\u0005    /%DCN005%/
		\u0024    /%DCN036%/
		\u0060    /%DCN096%/
		\u007C    /%DCN124%/
		\u007E    /%DCN126%/
	} $key
}

set lock {T&AUreb/M_2Wtp_lZU)EA_yU_)2[2/_4u:,`L`3\m:+ctsnyw9@}
set rkey \u0082'vArqp\u00d4&!\u00d6V2@\u00f23c\u00f0\u00c7\u00c6@\u00e1b\u00c2\u00a0g\u00b1\u0096\u0096\u00d1\u0007\u00b6\u0014\u00f4a\u00c4\u00c2\u00c25\u00f6\u0013u\u0011\u0084qp\u00d1q\u00e0\u00e4\u0097

set key [genkey $lock]
if {![string equal $key $rkey]} {
	puts stderr "FAILED\n\
		REF: $rkey\n\
		OUR: $key"
} else {
	puts "OK, [time {genkey $lock} 100]"
}
